package cn.ming.wfchat.app.dialog;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.view.KeyEvent;
import android.view.View;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;

import java.io.File;
import java.text.NumberFormat;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.databinding.ViewDataBinding;
import cn.ming.wfchat.R;
import cn.ming.wfchat.app.me.activity.model.VersionBean;
import cn.ming.wfchat.app.utils.ApkUtils;
import cn.ming.wfchat.app.utils.LogDownloadListener;
import cn.ming.wfchat.databinding.UpgradeDialogBinding;
import cn.ming.wfchat.kit.dialog.CenterDialog;
import cn.ming.wfchat.kit.utils.Tools;


/**
 * @Author luoming
 * @Date 2019/3/14 10:32 AM
 * 版本升级
 */
public class VersionUpgradeDialog extends CenterDialog {

    private static final String VERSION = "version";
    private UpgradeDialogBinding binding;
    private ProgressDialog mProgDialog;
    private VersionBean bean;
    Dialog dialog;
    private DownloadTask task;
    private NumberFormat numberFormat;
    public SharedPreferences mSavePreferencesData;

    /**
     * 定义结果回调接口
     */
    public interface OnClickListener {
        void successful(String paymentVoucher);

    }


    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        dialog = new Dialog(getActivity(), R.style.DialogStyle);
        if (dialog.getWindow() != null) {
            dialog.getWindow().setDimAmount(0.65f);
        }
        ViewDataBinding binding = getLayoutBind();
        View view = binding.getRoot();
        dialog.setContentView(view);
        initView(binding);
        initWindowParams(dialog);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    return true;
                }
                return false;
            }
        });

        return dialog;
    }

    @Override
    public Dialog getDialog() {
        return dialog;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    public void show(Object object) {
        try {
            super.show(object);
        } catch (IllegalStateException var5) {
        }

    }

    public static VersionUpgradeDialog newInstance(VersionBean bean) {
        VersionUpgradeDialog dialog = new VersionUpgradeDialog();
        Bundle bundle = new Bundle();
        bundle.putSerializable(VERSION, bean);
        dialog.setArguments(bundle);
        return dialog;
    }


    @Override
    public void dismiss() {
        super.dismissAllowingStateLoss();
    }


    @Override
    public int getLayoutId() {
        return R.layout.upgrade_dialog;
    }


    @Override
    public void initView(ViewDataBinding dataBinding) {
        binding = (UpgradeDialogBinding) dataBinding;
        numberFormat = NumberFormat.getPercentInstance();
        numberFormat.setMinimumFractionDigits(2);
        Bundle bundle = getArguments();
        if (bundle != null) {
            bean = (VersionBean) bundle.getSerializable(VERSION);
        }
        mSavePreferencesData = getActivity().getSharedPreferences("config", Context.MODE_PRIVATE);
        mProgDialog = new ProgressDialog(VersionUpgradeDialog.this.getActivity());
        mProgDialog.setCancelable(false);
        binding.tvCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        if (bean.getUpdateType() == 1) {
            binding.tvCancle.setVisibility(View.GONE);
        } else {
            binding.tvCancle.setVisibility(View.VISIBLE);
        }
        binding.tvTitle.setText("发现新版本" + bean.getVersionName());
        binding.tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(bean.getUpdateUrl())) {
                    initPermission();
                } else {
                    Tools.showToast(getActivity(), "APK下载地址为空");
                }
            }
        });
        binding.tvCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (task != null) {
                    task.pause();
                }
                //保存这个时间
                long quxiaotime = System.currentTimeMillis();
                mSavePreferencesData.edit().putLong("quxiaotime", quxiaotime).apply();
                dismissAllowingStateLoss();
            }
        });

        // 写法一：从内存中获取
        if (OkDownload.getInstance().hasTask(bean.getUpdateUrl())) {
            task = OkDownload.getInstance().getTask(bean.getUpdateUrl())//
                    .register(new DesListener("DesListener"))//
                    .register(new LogDownloadListener());
        }
    }

    private void refreshUi(Progress progress) {
        String currentSize = Formatter.formatFileSize(getActivity(), progress.currentSize);
        String totalSize = Formatter.formatFileSize(getActivity(), progress.totalSize);
        String speed = Formatter.formatFileSize(getActivity(), progress.speed);
        //binding.tvContext.setText(currentSize + "/" + totalSize + "  " + String.format("%s/s", speed) + "  " + numberFormat.format(progress.fraction));

        binding.pbProgressbar.setMax(10000);
        binding.pbProgressbar.setProgress((int) (progress.fraction * 10000));
        switch (progress.status) {
            case Progress.NONE:
                binding.tvOk.setText("下载");
                break;
            case Progress.LOADING:
                binding.tvOk.setText("暂停");
                break;
            case Progress.PAUSE:
                binding.tvOk.setText("继续");
                break;
            case Progress.WAITING:
                binding.tvOk.setText("等待");
                break;
            case Progress.ERROR:
                binding.tvOk.setText("出错");
                break;
            case Progress.FINISH:
                binding.tvOk.setText("安装");
                break;
        }
    }


    private void initPermission() {
        AndPermission.with(getActivity())
                .runtime()
                .permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE).
                onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> data) {
                        // binding.tvContext.setVisibility(View.GONE);
                        binding.llProgres.setVisibility(View.VISIBLE);
                        if (task == null) {

                            //这里只是演示，表示请求可以传参，怎么传都行，和okgo使用方法一样
                            GetRequest<File> request = OkGo.<File>get(bean.getUpdateUrl())//
                                    .headers("aaa", "111")//
                                    .params("bbb", "222");

                            task = OkDownload.request(bean.getUpdateUrl(), request)//
                                    .priority(1)//
                                    .save()//
                                    .register(new DesListener("DesListener"))//
                                    .register(new LogDownloadListener());
                        }
                        switch (task.progress.status) {
                            case Progress.PAUSE:
                            case Progress.NONE:
                            case Progress.ERROR:
                                task.start();
                                break;
                            case Progress.LOADING:
                                task.pause();
                                break;
                            case Progress.FINISH:
//                                File file = new File(task.progress.filePath);
//                                if (ApkUtils.isAvailable(this, file)) {
//                                    ApkUtils.uninstall(this, ApkUtils.getPackageName(this, file.getAbsolutePath()));
//                                } else {
//                                    ApkUtils.install(this, file);
//                                }
                                File file = new File(task.progress.filePath);
                                ApkUtils.install(getActivity(), file);
                                dismissAllowingStateLoss();
                                break;
                        }
                    }
                }).
                onDenied(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> data) {
                        Tools.showToast(getActivity(), "无法获取手机权限，功能无法正常使用");
                    }
                }).
                start();

    }

    private class DesListener extends DownloadListener {

        DesListener(String tag) {
            super(tag);
        }

        @Override
        public void onStart(Progress progress) {
        }

        @Override
        public void onProgress(Progress progress) {
            refreshUi(progress);
        }

        @Override
        public void onFinish(File file, Progress progress) {
            ApkUtils.install(getActivity(), file);
            dismissAllowingStateLoss();
        }

        @Override
        public void onRemove(Progress progress) {
        }

        @Override
        public void onError(Progress progress) {
            Throwable throwable = progress.exception;
            if (throwable != null) throwable.printStackTrace();
        }
    }
}
